const { app, BrowserWindow, Menu, screen, dialog } = require('electron');
const path = require('path');
const spawn = require('cross-spawn');
const treeKill = require('tree-kill');
const fs = require('fs');
// const isDev = require('electron-is-dev');
var isDev = false;

let mainWindow;
let nextProcess;
var port = 35999;

var time;

function createWindow() {
  // 获取主屏幕信息
  const { workAreaSize } = screen.getPrimaryDisplay();
  const { width, height } = workAreaSize;

  var minWidth = 1100;
  var minHeight = 600;

  // 计算 80% 的宽度和高度
  let windowWidth = Math.round(width * 0.8);
  let windowHeight = Math.round(height * 0.8);

  if (windowWidth < minWidth) windowWidth = minWidth;
  if (windowHeight < minHeight) windowHeight = minHeight;

  mainWindow = new BrowserWindow({
    width: windowWidth,
    height: windowHeight,
    minWidth: minWidth,
    minHeight: minHeight,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  Menu.setApplicationMenu(null);

  // 加载 loading
  mainWindow.loadURL(`file://${path.join(__dirname, 'loading.html')}`);

  time = setTimeout(() => {
    renderPage();
  }, 3000);
}

function renderPage() {
  if (time) {
    clearInterval(time);
  }
  mainWindow.loadURL(`http://localhost:${port}`);
}

async function startNext() {
  // 获取当前打包的路径
  const appPath = app.getAppPath();

  try {
    const nextPath = path.join(appPath, 'node_modules', '.bin', 'next');
    const env = {
      ...process.env,
      PROJECT_START: '1',
      NODE_ENV: 'production',
    };

    nextProcess = spawn(nextPath, ['start', '-p', String(port)], {
      cwd: appPath,
      stdio: 'pipe',
      shell: true,
      env,
    });

    nextProcess.stdout.on('data', (data) => {
      console.log(`Next.js stdout: ${data}`);
      if (data.indexOf('Ready in') !== -1) {
        renderPage();
      }
    });

    nextProcess.stderr.on('data', (data) => {
      const errorMessage = `Next.js Error: ${data}`;
      console.error(errorMessage);
      dialog.showErrorBox('Next.js Error', errorMessage);
    });

    nextProcess.on('error', (err) => {
      const errorMessage = `Failed to start Next.js process: ${err}`;
      console.error(errorMessage);
      dialog.showErrorBox('Next.js Process Error', errorMessage);
    });

    nextProcess.on('exit', (code) => {
      const exitMessage = `Next.js process exited with code ${code}`;
      console.log(exitMessage);
      dialog.showErrorBox('Next.js Process Exit', exitMessage);
    });
  } catch (error) {
    const errorMessage = `Error starting Next.js: ${error.message}`;
    console.error(errorMessage);
    dialog.showErrorBox('Error', errorMessage);
  }
}

async function closeNext() {
  if (!nextProcess) {
    console.log('Next.js process not started.');
    return;
  }

  console.log('Killing Next.js process...');

  try {
    if (process.platform === 'win32') {
      // Windows 下用 taskkill 强制杀掉整个进程树
      await new Promise((resolve, reject) => {
        const { exec } = require('child_process');
        exec(
          `taskkill /PID ${nextProcess.pid} /T /F`,
          (err, stdout, stderr) => {
            if (err) {
              console.error('Error taskkilling Next.js process:', err);
              reject(err);
            } else {
              console.log('Next.js process killed with taskkill.');
              resolve();
            }
          },
        );
      });
    } else {
      // 其他平台继续用 tree-kill，尝试 SIGKILL
      await new Promise((resolve, reject) => {
        treeKill(nextProcess.pid, 'SIGKILL', (err) => {
          if (err) {
            console.error('Error killing Next.js process:', err);
            reject(err);
          } else {
            console.log('Next.js process killed.');
            resolve();
          }
        });
      });
    }
  } catch (error) {
    console.error('Failed to kill Next.js process:', error);
  } finally {
    nextProcess = null;
  }
}

app.whenReady().then(() => {
  createWindow();
  if (!isDev) {
    startNext();
  }

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

let isQuitting = false;

app.on('before-quit', async (event) => {
  if (!isQuitting) {
    event.preventDefault();
    console.log('Application is quitting...');
    isQuitting = true;
    await closeNext();
    app.quit();
  }
});

app.on('window-all-closed', async () => {
  console.log('All windows closed');
  if (process.platform!== 'darwin') {
    if (!isQuitting) {
      isQuitting = true;
      await closeNext();
      app.quit();
    }
  }
});
    